package com.kly.chatter.api.application.service.impl;

import com.fqgj.base.services.redis.RedisClient;
import com.kly.chatter.api.application.controller.im.rsp.PpvMessageRsp;
import com.kly.chatter.api.application.service.MessageService;
import com.kly.chatter.api.application.utils.Result;
import com.kly.sc.api.application.constant.ApiRedisKeys;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.user.dto.UserBaseDto;
import com.kly.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {


    @Resource
    private RedisClient redisClient;

    @Resource
    private UserService userService;

    @Override
    public Result<PpvMessageRsp> ppvMessage(String userCode, int ppvType) {

        PpvMessageRsp ppvMessage = new PpvMessageRsp();
        ppvMessage.setStatus(0);

        UserBaseDto userBaseDto = RpcUtils.getResult(userService.getUserBaseInfo(userCode));
        if (userBaseDto != null && (StringUtils.isEmpty(userBaseDto.getChannel()) || userBaseDto.getChannel().equals("Organic"))) {
            return Result.ok(ppvMessage);
        }

        Object object = redisClient.get(ApiRedisKeys.PPV_MSG.getValue(), userCode, String.valueOf(ppvType));
        if (object != null) {
            return Result.ok(ppvMessage);
        }

        ppvMessage.setStatus(0);
        if (ppvType == 1) {
            ppvMessage.setMessage("I just sent you an exclusive and juicy secret!\uD83D\uDCA6");
        } else {
            ppvMessage.setMessage("I just sent you an exclusive private video!\uD83C\uDF51");
        }

        LocalDateTime now = LocalDateTime.now();
        // 设置时间为当天的最后时刻（23:59:59）
        LocalTime endOfDay = LocalTime.of(23, 59, 59);
        // 计算当前时间到当天最后时刻的时间差
        long remainingSeconds = now.until(LocalDateTime.of(now.toLocalDate(), endOfDay), ChronoUnit.SECONDS);
        redisClient.set(ApiRedisKeys.PPV_MSG.getValue(), userCode, (24 * 60 * 60 * 2) + remainingSeconds, userCode, String.valueOf(ppvType));

        return Result.ok(ppvMessage);
    }
}
